#include <stdlib.h>
#include <iostream>
using std::cout;
using std::endl;

//第三种方案: atexit + destroy

class Singleton
{
public:
    //多线程环境下，并不能保证线程安全
    static Singleton * getInstance()
    {   //加锁
        if(_pInstance == nullptr){
            atexit(destroy);
            _pInstance = new Singleton();
        }
        return _pInstance;
    }
    
    static void destroy()
    {
        if(_pInstance) {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

    int getData() const {   return _data;   }

private:
    Singleton() {   cout << "Singleton()" << endl;  }
    ~Singleton() {  cout << "~Singleton()" << endl;}

    friend class AutoRelease;
private:
    int _data = 0;
    static Singleton * _pInstance;
};

//初始化操作是在进入main函数之前完成的
//Singleton * Singleton::_pInstance = nullptr;//懒汉/饱汉(懒加载)模式
Singleton * Singleton::_pInstance = getInstance();//饿汉模式


void test0()
{
    cout << "test0 method3" << endl;
    Singleton * p1 = Singleton::getInstance();
    Singleton * p2 = Singleton::getInstance();
    cout << "p1:" << p1 << endl;
    cout << "p2:" << p2 << endl;
    cout << p1->getData() << endl;
    cout << p2->getData() << endl;

}


int main()
{
    test0();
    return 0;
}

